<template>
  <div>
    <div class="div_top">
      <el-steps :active="itemActive" :align-center="true" finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="课程简介"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
    </div>
    <div style="text-align: left">
        <div class="div_option"
             v-loading="loading">
          <div v-if="base_info">
            <el-form  label-position="left"
                      label-width="100px"
                      :model="courseData"
                      :rules="base_info_rules"
                      ref="base_info_form">
              <el-form-item label="课程名称"
                            prop="title">
                <el-input v-model="courseData.title"
                          style="width: 500px"
                          maxlength="30"
                          show-word-limit
                          auto-complete="off">
                </el-input>
              </el-form-item>
              <el-form-item label="课程方向" prop="directionId">
                <el-select v-model="courseData.directionId" filterable placeholder="请选择" >
                  <el-option
                    v-for="item in directions"
                    :key="item.directionId"
                    :label="item.name"
                    :value="item.directionId">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="课程分类"  prop="sortId">
                <el-select v-model="courseData.sortId" filterable placeholder="请选择">
                  <el-option
                    v-for="item in sorts"
                    :key="item.sortId"
                    :label="item.name"
                    :value="item.sortId">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="课程难度" prop="difficulty">
                <el-select v-model="courseData.difficulty" placeholder="请选择" >
                  <el-option
                    v-for="item in difficultys"
                    :key="item.difficulty"
                    :label="item.name"
                    :value="item.difficulty">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="上传图片" prop="imageUrl">
                <el-input type="hidden" v-model="courseData.imageUrl"></el-input>
                <el-upload
                  list-type="picture-card"
                  :http-request="fileUpload"
                  :auto-upload="true"
                  :action="ossData.host"
                  :limit="1"
                >
                  <i slot="default" class="el-icon-plus"></i>
                  <div slot="file" slot-scope="{file}">
                    <img
                      class="el-upload-list__item-thumbnail"
                      :src="file.url" alt=""
                    >
                    <span class="el-upload-list__item-actions">
                  <span
                    class="el-upload-list__item-preview"
                    @click="handlePictureCardPreview(file)">
                    <i class="el-icon-zoom-in"></i>
                  </span>
                  <span
                    v-if="!disabled"
                    class="el-upload-list__item-delete"
                    @click="handleRemove(file)"
                  >
                    <i class="el-icon-delete"></i>
                  </span>
                </span>
                  </div>
                </el-upload>
                <el-dialog :visible.sync="dialogVisible" :alignCenter="true">
                  <img width="100%" :src="dialogImageUrl" alt="">
                </el-dialog>
              </el-form-item>
            </el-form>
          </div>
          <div v-if="course_detail">
            <el-form  label-position="left"
                      label-width="100px"
                      :model="courseData"
                      :rules="course_detail_rules"
                      ref="course_detail_form">
            <el-form-item label="课程简介" prop="introduction">
              <el-input type="textarea"
                        placeholder="请输入内容"
                        v-model="courseData.introduction"
                        maxlength="200"
                        show-word-limit
                        class="textarea"
              >
              </el-input>
            </el-form-item>
            <el-form-item label="课程须知" prop="notice">
              <el-input type="textarea"
                        placeholder="请输入内容"
                        v-model="courseData.notice"
                        maxlength="200"
                        show-word-limit
                        class="textarea"
              >
              </el-input>
            </el-form-item>
              <el-form-item label="一句话说" prop="hotWord">
                <el-input type="textarea"
                          placeholder="请输入内容"
                          v-model="courseData.hotWord"
                          maxlength="50"
                          show-word-limit
                          class="textarea"
                >
                </el-input>
              </el-form-item>
            <el-form-item label="老师提醒" prop="teacherNotice">
              <el-input type="textarea"
                        placeholder="请输入内容"
                        v-model="courseData.teacherNotice"
                        maxlength="200"
                        show-word-limit
                        class="textarea"
              >
              </el-input>
            </el-form-item>
            </el-form>
          </div>
          <div v-if="save_success" style="height: 300px;text-align: center;vertical-align: middle;font-size: 50px;color: #67C23A;padding-top: 50px">
            <i class="el-icon-success">
            </i>
            <br>
            <span>
              完成</span>
          </div>
        </div>

        <el-divider ></el-divider>
        <div>
          <el-button v-if="itemActive == 1" style="float: left" type="info" @click="before">上一步</el-button>
          <el-button v-if="itemActive == 0" style="float: right" type="primary" @click="next">下一步</el-button>
          <el-button v-if="itemActive == 1" style="float: right" type="success" @click="next" >提交</el-button>
        </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'CreateCourse',
  data () {
    return {
      itemActive: 0,
      loading: false,
      base_info: true,
      course_detail: false,
      save_success: false,
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      courseData: {
        title: '',
        directionId: '',
        sortId: '',
        difficulty: 1,
        imageUrl: '',
        introduction: '',
        notice: '',
        teacherNotice: '',
        userId: '',
        hotWord: ''
      },
      directions: [
      ],
      sorts: [],
      difficultys: [
        {
          difficulty: 1,
          name: '入门'
        },

        {
          difficulty: 2,
          name: '初级'
        },
        {
          difficulty: 3,
          name: '中级'
        },
        {
          difficulty: 4,
          name: '高级'
        }
      ],
      ossData: {
        accessid: '',
        policy: '',
        signature: '',
        dir: '',
        host: 'http://cdn.404zz.cn',
        expire: '',
        callback: ''
      },
      progress: 0,
      base_info_rules: {
        title: [
          { required: true, message: '请输入课程名称', trigger: 'blur' }
        ],
        directionId: [
          {
            required: true, message: '请选择课程方向', trigger: 'change'
          }
        ],
        sortId: [
          {
            required: true, message: '请选择课程分类', trigger: 'change'
          }
        ],
        difficulty: [
          {
            required: true, message: '请选择课程难度', trigger: 'change'
          }
        ],
        imageUrl: [
          {
            required: true, message: '请上传课程图片'
          }
        ]

      },
      course_detail_rules: {
        introduction: [
          {required: true, message: '请输入课程简介', trigger: 'change'}
        ],
        notice: [
          {required: true, message: '请输入课程须知', trigger: 'change'}
        ],
        teacherNotice: [
          {required: true, message: '请输入老师提醒', trigger: 'change'}
        ],
        hotWord: [
          {required: true, message: '请输入一句话说', trigger: 'change'}
        ]
      }
    }
  },
  watch: {
    'courseData.directionId': function (newValue) {
      this.getSortByDirectionId()
    },
    'courseData.sortId': function (newValue) {
      this.getDirectionBySortId()
    }
  },
  mounted () {
    this.getAllDirection()
    this.getAllSort()
  },
  methods: {
    handleRemove (file) {
    },
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    getAllDirection () {
      var _this = this
      this.$axios.post('/api/direction/getAllDirection')
        .then(function (response) {
          var data = response.data
          if (data) {
            _this.directions = _this.$qs.parse(data.result)
          }
        })
    },
    getAllSort () {
      this.courseData.userId = this.$store.state.user.userId
      var _this = this
      this.$axios.post('/api/sort/getAllSort')
        .then(function (response) {
          var data = response.data
          if (data) {
            _this.sorts = _this.$qs.parse(data.result)
          }
        })
    },
    getSortByDirectionId () {
      var _this = this
      this.$axios.post('/api/sort/getSortByDirection',
        this.$qs.stringify({
          directionId: this.courseData.directionId
        }))
        .then(function (response) {
          var data = response.data
          if (data) {
            _this.sorts = _this.$qs.parse(data.result)
          }
        })
    },
    getDirectionBySortId () {
      var _this = this
      this.$axios.post('/api/direction/getDirectionBySort',
        this.$qs.stringify({
          sortId: this.courseData.sortId
        }))
        .then(function (response) {
          var data = response.data
          if (data) {
            _this.courseData.directionId = _this.$qs.parse(data.result).directionId
          }
        })
    },
    before () {
      // eslint-disable-next-line eqeqeq
      if (this.itemActive == 1) {
        this.itemActive = this.itemActive - 1
        this.course_detail = false
        this.base_info = true
        // eslint-disable-next-line eqeqeq
      }
    },
    next () {
      // eslint-disable-next-line eqeqeq
      if (this.itemActive == 0) {
        this.$refs['base_info_form'].validate((valid) => {
          if (valid) {
            this.itemActive = this.itemActive + 1
            this.base_info = false
            this.course_detail = true
          } else {
            return false
          }
        })
        // eslint-disable-next-line eqeqeq
      } else if (this.itemActive == 1) {
        this.$refs['course_detail_form'].validate((valid) => {
          if (valid) {
            this.createCourse()
          } else {
            return false
          }
        })
      }
    },
    async fileUpload (file) {
      var _this = this
      var host = this.$store.state.ossData.host
      var response = this.$Utils.getSignature('image')
      var requestData = new FormData()
      await response.then(res => {
        requestData = this.$Utils.fileUpload(file.file, res)
      })
      await this.$axios.post(host, requestData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        onUploadProgress: progressEvent => {
          let complete = (progressEvent.loaded / progressEvent.total * 100 | 0)
          file.onProgress({percent: complete})
          // _this.progress = complete
        }
      })
        .then(function (response) {
          // eslint-disable-next-line eqeqeq
          if (response.status == 200) {
            _this.courseData.imageUrl = host + '/' + requestData.get('key')
          }
        })
    },
    createCourse () {
      this.loading = true
      var _this = this
      var courseData = this.courseData
      this.$delete(courseData, 'directionId')
      this.$axios.post('/api/course/addCourse',
        this.$qs.stringify({
          courseData: JSON.stringify(courseData)
        }))
        .then(function (response) {
          _this.loading = false
          var data = response.data
          if (data.isSuccess) {
            _this.itemActive = _this.itemActive + 2
            _this.course_detail = false
            _this.save_success = true
          } else {
            _this.$message({
              message: '系统出错，请联系管理员',
              type: 'warning'
            })
          }
        })
        // eslint-disable-next-line handle-callback-err
        .catch(function (error) {
          _this.loading = false
          _this.$message.error('系统错误，请联系管理员')
        })
    }
  }
}
</script>

<style scoped>
.div_top{
  width: 100%;
}
.div_option{
  height: auto;
  padding: 20px;
}
  .textarea{
    width: 500px;
  }
</style>
